﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp.UI;
using CPPProject.CPP.Dto;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CPPProject.CPP
{
    public class CPPContractAppService : AsyncCrudAppService<CPPContract, CPPContractDto, Guid, PagedResultRequestDto, CreateCPPContractDto, UpdateCPPContractDto>
    {
        private readonly IObjectMapper _objectMapper;
        private readonly ICPPContractDetailAppService _cPPContractDetailAppService;
        private readonly ICPPCustomerAppService _cPPCustomerAppService;
        private readonly ICPPSequenceAppService _cPPSequenceAppService;
        public CPPContractAppService(
            IRepository<CPPContract, Guid> repository,
            IObjectMapper objectMapper,
            ICPPContractDetailAppService cPPContractDetailAppService,
            ICPPCustomerAppService cPPCustomerAppService,
            ICPPSequenceAppService cPPSequenceAppService) : base(repository)
        {
            _objectMapper = objectMapper;
            _cPPContractDetailAppService = cPPContractDetailAppService;
            _cPPCustomerAppService = cPPCustomerAppService;
            _cPPSequenceAppService = cPPSequenceAppService;
        }
        /// <summary>
        /// 查询合同列表
        /// </summary>
        /// <param name="skipCount">跳过条数/param>
        /// <param name="maxResultCount">单次最大查询条数</param>
        /// <param name="contractNum">合同编号</param>
        /// <param name="bizType">业务类型（0期租1次租2贸易）</param>
        /// <param name="startDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <param name="customer">客户Id</param>
        /// <param name="paymentMtd">结算方式（月结，季度结算，年度结算）</param>
        /// <param name="status">状态（0未执行1执行中2已关闭）</param>
        /// <returns></returns>
        public async Task<PagedResultDto<CPPContractDto>> GetList(int skipCount = 0, int maxResultCount = 10, string contractNum = "", string bizType = "", string startDate = "", string endDate = "", string customer = "", string paymentMtd = "", string status = "")
        {
            PagedResultDto<CPPContractDto> resultDto = new PagedResultDto<CPPContractDto>();
            List<CPPContract> lists = new List<CPPContract>();
            Expression<Func<CPPContract, bool>> expr = o => 1 == 1;
            if (!string.IsNullOrEmpty(contractNum))
            {
                expr = expr.ExpressionAnd(o => o.ContractNum == contractNum);
            }
            if (!string.IsNullOrEmpty(bizType))
            {
                expr = expr.ExpressionAnd(o => o.BizType == bizType);
            }
            if (!string.IsNullOrEmpty(startDate))
            {
                expr = expr.ExpressionAnd(o => o.StartDate.Day.ToString() == startDate);
            }
            if (!string.IsNullOrEmpty(endDate))
            {
                expr = expr.ExpressionAnd(o => o.EndDate.Day.ToString() == endDate);
            }
            if (!string.IsNullOrEmpty(customer))
            {
                expr = expr.ExpressionAnd(o => o.CustomerId.ToString() == customer);
            }
            if (!string.IsNullOrEmpty(paymentMtd))
            {
                expr = expr.ExpressionAnd(o => o.PaymentMtd == paymentMtd);
            }
            if (!string.IsNullOrEmpty(status))
            {
                expr = expr.ExpressionAnd(o => o.Status == status);
            }
            if (expr != null)
            {
                var dtos = await Repository.GetAll().Where(expr).OrderByDescending(o => o.CreationTime).Skip(skipCount).Take(maxResultCount).ToListAsync();
                resultDto.Items = _objectMapper.Map<List<CPPContractDto>>(dtos);
                resultDto.TotalCount = lists.Count;
                foreach (var item in resultDto.Items)
                {
                    item.Dtllist = await _cPPContractDetailAppService.GetById(item.ContractNum);
                    var com = await _cPPCustomerAppService.GetById(item.CustomerId.ToString());
                    item.Name = com.Name;
                }
            }
            else
            {
                resultDto = await base.GetAllAsync(new PagedResultRequestDto { MaxResultCount = maxResultCount, SkipCount = skipCount });
            }
            return resultDto;
        }
        /// <summary>
        /// 批量删除合同
        /// </summary>
        /// <param name="id">标识Id</param>
        /// <param name="dtlid">合同明细标识Id</param>
        /// <returns></returns>
        public async Task BatchDelete(string id, string dtlid)
        {
            if (!string.IsNullOrEmpty(id))
            {
                await Repository.DeleteAsync(o => id.Contains(o.Id.ToString()));
            }
            if (!string.IsNullOrEmpty(dtlid))
            {
                await _cPPContractDetailAppService.BatchDeleteDtl(dtlid);//删除合同明细
            }
            #region （旧）循环删除
            //string[] obj = id.Split(",");
            //for (int i = 0; i < obj.Length; i++)
            //{
            //    await Repository.DeleteAsync(Guid.Parse(obj[i]));
            //}
            #endregion
        }

        /// <summary>
        /// 批量修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state">状态（0未执行1执行中2已关闭）</param>
        /// <returns></returns>
        public async Task<bool> BatchChangeStatus(string id, string state)
        {
            string[] obj = id.Split(",");
            for (int i = 0; i < obj.Length; i++)
            {
                var list = await Repository.GetAll().Where(o => o.Id.ToString() == obj[i]).FirstOrDefaultAsync();
                list.Status = state;
            }
            return true;
        }
        /// <summary>
        /// 重写 创建合同接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<CPPContractDto> CreateAsync(CreateCPPContractDto input)
        {
            var list = await Repository.GetAll().Where(o => o.ContractNum == input.ContractNum).ToListAsync();//生成合同编号并返回
            if (list.Count <= 0)
            {
                var contractNum = _cPPSequenceAppService.GetRequestNo("ContractNum", true);
                input.ContractNum = contractNum;
                return await base.CreateAsync(input);
            }
            else
            {
                throw new UserFriendlyException(input.ContractNum + "已经存在");
            }

        }
    }
}
